package com.itheima.reggie.controller;

import cn.hutool.core.lang.UUID;
import com.itheima.reggie.common.R;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${reggie.filePath}")
    private String filePath;



    /**
     * 图片上传的接口
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R upLoad(@RequestBody MultipartFile file){
        //获取原始文件名
        String originalFilename = file.getOriginalFilename();
        //uuid作为文件名
        String fileName = UUID.randomUUID().toString();
        //讲原始文件名进行截取,获得'.'后面的内容,即jpg
        String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
        //拼接uuid以及.jpg获取最终图片名称
        fileName=fileName+suffixName;
        //判断路径下的文件是否存在,如果不存在,创建
        File dir = new File(filePath);
        if(!dir.exists()){
            dir.mkdirs();
        }
        try {
            file.transferTo(new File(filePath,fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(fileName);
    }

    /**
     * 图片下载的接口
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download( String name,HttpServletResponse response ){

        try {
            //固定用法
            response.setContentType("image/jpeg");//设置类型,告诉浏览器
            //输入流读取文件内容
            FileInputStream fileInputStream = new FileInputStream(new File(filePath+name));
            //输出流写回文件
            ServletOutputStream outputStream = response.getOutputStream();
            //简化书写,不怕麻烦可以一步一步读取
            IOUtils.copy(fileInputStream,outputStream);
            fileInputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
